package com.paco.study.cloud.user.service.impl;

import com.paco.study.cloud.user.dao.TokenDao;
import com.paco.study.cloud.user.model.Token;
import com.paco.study.cloud.user.service.TokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    @Override
    public String searchEmailByCode(String token) {
        Token t = tokenDao.findByToken(token);
        if (t == null) {
            return null;
        }
        return t.getEmail();
    }

    @Override
    public Boolean isRegistered(String email) {
        Token t = tokenDao.findByEmail(email);
        return t != null && StringUtils.isNotEmpty(t.getEmail());
    }

    @Override
    public String login(String email, String password, HttpServletResponse response) {
        //验证密码和账号
        Token to = tokenDao.findByEmail(email);

        if (to == null) {
            return null;
        }

        if (StringUtils.equals(to.getToken(), generateToken(email, password))) {
            writeSession(response, to.getToken());
            return to.getEmail();
        }

        return null;

    }


    @Override
    public Boolean register(String email, String password, String code, HttpServletResponse response) {

//        校验验证码

        //如果已注册，注册失败
        Token to = tokenDao.findByEmail(email);

        if (to != null) {
            return false;
        }

        to = new Token();
        to.setEmail(email);
        to.setToken(generateToken(email, password));
        tokenDao.saveAndFlush(to);

        writeSession(response, to.getToken());

        return true;
    }

//    生成token
    private String generateToken(String email, String password) {
        return (UUID.nameUUIDFromBytes((email).getBytes()).toString() +
                "-" +
                UUID.nameUUIDFromBytes((password).getBytes()).toString());

    }

//    写入cookie
    public void writeCookie(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    @Override
    public void writeSession(HttpServletResponse response, String token) {
        writeCookie(response, "mySession", token);
    }

}
